package com.grapecity.forguncy.utils;

import com.grapecity.forguncy.commands.entity.Command;

import java.net.URL;
import java.net.URLClassLoader;

public class AdapterClassLoader extends URLClassLoader {
    private final Class<Command> cls;

    /**
     * 构造函数
     *
     * @param urls         路径列表
     * @param commandClass
     */
    public AdapterClassLoader(URL[] urls, Class<Command> commandClass) {
        super(urls, null);
        cls = commandClass;
    }

    @Override
    protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
        try {
            // 如果是Forguncy提供的jar包类，直接使用默认类加载器加载
            return cls.getClassLoader().loadClass(name);
        } catch (ClassNotFoundException e) {
            // 如果加载失败，肯能是用户开发的插件中使用了类似Forguncy的包名，这时候使用自定义类加载器加载
            return loadExternalClass(name, resolve);
        }
    }

    private Class<?> loadExternalClass(String name, boolean resolve) {
        // Check if the class has already been loaded
        Class<?> clazz = findLoadedClass(name);
        if (clazz != null) {
            return clazz;
        }

        try {
            // Load the class using this class loader
            clazz = findClass(name);
        } catch (ClassNotFoundException | NoClassDefFoundError e) {
            // If the class can't be found, delegate to the parent class loader
            try {
                clazz = super.loadClass(name, resolve);
            } catch (ClassNotFoundException | NoClassDefFoundError ex) {
                System.out.println(ex.getMessage());
            }
        }

        if (resolve) {
            resolveClass(clazz);
        }
        return clazz;
    }
}
